<script lang="ts" setup>
import PageHeader from "@/views/Common/PageHeader.vue";
import NavigationBarStricky from "@/views/Common/NavigationBarSticky.vue";
import NavigationBar from "@/views/Common/NavigationBar.vue";
import {onMounted, ref, watch} from 'vue'
import SmallExpertInfoCard from "@/components/card/SmallExpertInfoCard.vue";
import {useRouter} from "vue-router";
import {getQuestionDetailAPI,getAllCommentsAPI,replyQuestionAPI,replyMoreQuestionAPI,getQuestionsByUidAPI} from '@/apis/expert'
import {getExpertsAPI} from "@/apis/home.js";
import {ElMessage} from "element-plus";
import {useUserStore} from '@/stores/user'

const replyDialogVisible=ref(false)
const replyText=ref('')
const userStore=useUserStore()

const router = useRouter()

onMounted(()=>{
  getQuestionDetail()
  getRelatedExpert()
})


async function getQuestionDetail(){
  const res=await getQuestionDetailAPI(router.currentRoute.value.params.qid)
  data.value=res.data
  //获取相关问答帖子
  getRelatedQuestion(res.data.uid)
  //获取评论
  const firstComment={
    eid:res.data.eid,
    avatar:'',
    name:res.data.expertName,
    message:res.data.answer,
    replyDate:res.data.expert_date
  }

  if(res.data.answer!==null)
    commentList.value.push(firstComment)

  const moreComments=await getAllCommentsAPI(res.data.qid)
  if (moreComments.data!==null){
    moreComments.data.forEach(item=>{
      const comment={
        eid:item.eid,
        avatar:'',
        name:item.userName,
        message:item.answer,
        replyDate:item.expert_date
      }
      commentList.value.push(comment)
    })
  }
}

watch(() =>
        router.currentRoute.value.path,
    (toPath) => {
      window.location.reload()
    },{immediate: false,deep: true})

const data=ref([])



const commentList=ref([])

const activeFloor = ref(1)
const headerOffset = 120
function scrollToFloor(i) {
  activeFloor.value = i
  const el = document.getElementById(`floor-${i}`)
  if (el) {
    const top = el.getBoundingClientRect().top + window.scrollY - headerOffset
    window.scrollTo({ top, behavior: 'smooth' })
  }
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp); // 创建日期对象
  const year = date.getFullYear(); // 获取年份
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份（注意月份从0开始）
  const day = String(date.getDate()).padStart(2, '0'); // 获取日期
  const hours = String(date.getHours()).padStart(2, '0'); // 获取小时
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒数

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // 返回格式化后的字符串
}

const relatedQuestionList=ref([])
const relatedExpertList=ref([])

async function getRelatedQuestion(uid) {
  const res=await getQuestionsByUidAPI(uid)
  //过滤
  relatedQuestionList.value=res.data.filter(item=>{
    return item.qid!==data.value.qid
  })
}
async function getRelatedExpert() {
  const res=await getExpertsAPI()
  relatedExpertList.value=res.data
}


async function handleReply() {
  if(!userStore.isLogin){
    ElMessage({
      type:'error',
      message:'请先登录'
    })
    return
  }

  if(replyText.value.length===0){
    ElMessage({
      type:'error',
      message:'内容不能为空'
    })
    return
  }
  const comment={
    qid:data.value.qid,
    uid:useUserStore().userInfo.uid,
    answer:replyText.value
  }
  const res=commentList.value.length===0?await replyQuestionAPI(comment):await replyMoreQuestionAPI(comment)
  if(res.code===200){
    commentList.value=[]
    await getQuestionDetail()
    replyDialogVisible.value=false
  }else{
    ElMessage({
      type:'error',
      message:'回复失败'
    })
  }
}
</script>

<template>
<div class="page">
  <div class="header-white">
    <NavigationBarStricky />
    <PageHeader />
    <navigation-bar></navigation-bar>
  </div>

  <!-- 右侧楼层锚点目录 + 返回顶部 -->
  <div class="qa-toc">
    <div class="toc-title">楼层导航</div>
    <div class="toc-list">
      <div
        v-for="(_, i) in commentList"
        :key="i"
        :class="['toc-item', {active: activeFloor === i + 1}]"
        @click="scrollToFloor(i + 1)"
      >
        第{{ i + 1 }}楼
      </div>
    </div>
  </div>
  <el-backtop :right="40" :bottom="60" />

  <div class="panel">
    <div class="upper">
      <div>
        <el-row>
          <el-badge value="问" color="#14c131" ></el-badge>
          {{ data.question }}
        </el-row>
        <el-row>
          <el-col :span="12" style="display: flex;align-items: center">
            <img style="width: 25px;height: 25px" src="@/assets/weixin.png">
            <span style="font-size: 14px;margin-left: 5px">{{ data.userName }}</span>
          </el-col>
          <el-col :span="12">
            <span style="float: right;font-size: 12px;color: #5f5f5f">提问于{{ formatTimestamp(data.created_date) }}</span>
          </el-col>
        </el-row>
        <el-row>
          <el-button class="replyBtn" @click="replyDialogVisible=true">回复</el-button>
        </el-row>
        <div style="width: 100%;height: 1px;background-color: rgba(112,112,114,0.15);margin-top: 10px;margin-bottom: 10px"></div>

        <div class="commentList" >
          <div v-for="(item, idx) in commentList" :id="`floor-${idx+1}`" :class="['comment-item', {active: activeFloor === idx + 1}]">

            <div style="display: flex;align-items: center">
              <img style="width: 30px;height: 30px" src="@/assets/weixin.png">
              <span style="font-size: 14px;margin-left: 5px">{{ item.name }}</span>
            </div>
            <div style="margin-top: 5px">
              <span style="margin-left: 10px">{{ item.message }}</span>
            </div>
            <div style="margin-top:5px;display: flex;flex-direction: column">
              <span style="margin-left: auto;font-size: 12px;color: #5f5f5f">{{formatTimestamp(item.replyDate)}}</span>
              <div style="width: 100%;height: 1px;background-color: rgba(67,69,70,0.06)"></div>
            </div>

          </div>
        </div>



        <div style="position: relative">

        </div>

        <el-dialog v-model="replyDialogVisible" title="回复" width="500">
          <el-input type="textarea" rows="8" v-model="replyText" placeholder="请输入文字">

          </el-input>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="replyDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleReply">
                确定
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>

    </div>

    <div class="center">
      <h3>相关专家问答</h3>
      <div class="questionList">

        <div class="ques-info" v-for="item in relatedQuestionList" @click="router.push(`/question/${item.qid}`)">
          <div class="question" style="margin-left: 5px;font-weight: bold;margin-top: 25px">
            <el-badge value="问" color="#14c131"></el-badge>
            <span class="qTitle">{{item.user_ques}}</span>
          </div>

          <div class="answer" style="margin-left: 5px;font-weight: bold;margin-top: 15px">
            <el-badge value="答" color="#ff862c"></el-badge>
            <span>{{item.expert_ans}}</span>
          </div>

          <div class="footer" style="margin-top: 5px">
<!--            <span style="float: left;margin-left: 50px">全部{{item.replies}}个回答</span>-->
            <span style="float: right;font-size: 12px">更新于{{ item.expert_date }}</span>
          </div>
        </div>

      </div>
    </div>

    <div class="bottom">
      <h3>相关专家推荐</h3>
      <div class="expertList">
        <SmallExpertInfoCard :experts="relatedExpertList"></SmallExpertInfoCard>
      </div>
    </div>
  </div>
</div>
</template>

<style scoped lang="less">
.page{
  background-color: #f5f5f5;
}
.panel{
  margin-left: auto;
  margin-right: auto;
  width: 1000px;
  height: auto;
  border-radius: 15px;

  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  gap: 30px;
}
.upper{
  width: 100%;
  min-height: 300px;
  height: auto;
  padding: 20px 10px;
  background-color: white;
  font-size: 18px;
  border-radius: 10px;
}
.center{
  width: 100%;
  min-height: 500px;
  height: auto;
  background-color: white;
  border-radius: 10px;
  padding: 10px 15px;
}
.bottom{
  width: 100%;
  height: auto;
  background-color: white;
  border-radius: 10px;
  padding: 10px 15px;
  margin-bottom: 30px;
}
.replyBtn{
  margin-left: auto;
  width: 180px;
  background-color: #39bf3e;
  color: white;
}
.questionList{
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  gap: 5px;
}
.ques-info:hover{
  cursor: pointer;
  .qTitle{
    color: #39bf3e;
  }
}
.commentList{
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  gap: 30px;
}
.header-white{
  background-color: #fff;
  width: 100%;
}

/* 版式与卡片统一优化（追加样式，安全覆盖） */
.header-white{
  background-color: #fff;
  width: 100%;
}

.page{
  min-height: 100vh;
  background-color: #f3f6f8;
  padding-bottom: 40px;
}

/* 主容器统一：最大宽度、居中、合理留白 */
.panel{
  max-width: 1160px;
  width: calc(100% - 40px);
  margin: 20px auto 0;
  gap: 20px;
}

/* 三个模块统一为白底圆角卡片 + 阴影 */
.upper,
.center,
.bottom{
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
}

/* 上部卡片内边距与行高 */
.upper{
  padding: 20px 18px;
  line-height: 1.6;
}

/* 中部、底部卡片内边距 */
.center,.bottom{
  padding: 16px 18px;
}

/* 评论列表可读性 */
.commentList{
  gap: 20px;
}
.commentList > div{
  padding: 8px 6px 12px;
}
.commentList .el-divider{
  margin: 8px 0;
}

/* 相关问答卡片视觉统一与悬浮反馈 */
.questionList{
  gap: 10px;
}
.ques-info{
  background: #fff;
  border: 1px solid #eef0f2;
  border-radius: 10px;
  padding: 12px 14px;
  transition: all .2s ease;
}
.ques-info:hover{
  border-color: #39bf3e;
  box-shadow: 0 6px 18px rgba(57,191,62,0.18);
}

/* 统一按钮主色与悬浮态 */
.replyBtn{
  margin-left: auto;
  width: 180px;
  background-color: #39bf3e;
  border-color: #39bf3e;
  color: #fff;
}
.replyBtn:hover{
  filter: brightness(0.95);
}

/* 统一标题高亮 */
.qTitle{
  font-weight: 600;
  color: #333;
}

/* 响应式收敛 */
@media (max-width: 1280px){
  .panel{
    width: calc(100% - 24px);
    margin: 16px auto 0;
  }
  .upper,.center,.bottom{
    border-radius: 10px;
  }
}
/* 楼层锚点目录与高亮 */
.qa-toc{
  position: fixed;
  right: 24px;
  top: 220px;
  width: 120px;
  background: #fff;
  border: 1px solid #eef0f2;
  border-radius: 10px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.06);
  padding: 10px 8px;
  z-index: 10;
}
.qa-toc .toc-title{
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
}
.qa-toc .toc-list{
  display: flex;
  flex-direction: column;
  gap: 6px;
  max-height: 320px;
  overflow: auto;
}
.qa-toc .toc-item{
  font-size: 13px;
  color: #555;
  padding: 6px 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: all .2s ease;
  border: 1px solid transparent;
}
.qa-toc .toc-item:hover{
  background: #f7fff8;
  border-color: #cbeed0;
  color: #2a9e2f;
}
.qa-toc .toc-item.active{
  background: #e9f9ec;
  border-color: #39bf3e;
  color: #39bf3e;
  font-weight: 600;
}

/* 评论楼层高亮 */
.comment-item.active{
  outline: 2px solid rgba(57,191,62,0.35);
  border-radius: 8px;
}

/* 小屏隐藏右侧目录避免遮挡 */
@media (max-width: 1280px){
  .qa-toc{ display:none; }
}

</style>